﻿using SaaS.Cache.Auths;
using SaaS.Cache.Systems;
using SaaS.Cache.Users;
using SaaS.Core;
using SaaS.Model.Dto.Sites;
using SaaS.Model.Dto.Users;
using SaaS.Model.Enums;
using SaaS.Model.Enums.Systems;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using XCore.Web.Jwt;

namespace Web.Client.Services.Users
{
    public class AdminAppService : ClientApplicationServiceBase
    {
        private readonly UserCacheService _userCacheService;
        private readonly AdminAuthCacheService _adminUserCacheService;
        private readonly SettingCacheService _settingCacheService;
        public AdminAppService(
            UserCacheService userCacheService,
            AdminAuthCacheService adminUserCacheService,
            SettingCacheService settingCacheService)
        {
            _userCacheService = userCacheService;
            _adminUserCacheService = adminUserCacheService;
            _settingCacheService = settingCacheService;
        }
        /// <summary>
        /// 登录后台
        /// </summary>
        /// <param name="userId">会员Id</param>
        /// <param name="tenantId">租户Id</param>
        /// <returns></returns>
        public string Login(int userId, int tenantId)
        {
            if (userId == 0) throw new ClientException("未登陆", ClientLoggerSource.LOGIN_REGISTER);
            if (tenantId == 0) throw new ClientException("未选择租户", ClientLoggerSource.LOGIN_REGISTER);
            //# 获取用户信息
            UserModel user = _userCacheService.GetUserInfo(userId);
            if (!user) throw new ClientException("会员信息错误", ClientLoggerSource.USER_ERROR);
            if (!user.Tenants.Contains(tenantId)) throw new ClientException("未配置租户", ClientLoggerSource.USER_ERROR);
            SiteModel tenant = new SiteModel();
            //# 获取租户管理员信息
            SiteAdminModel admin = new SiteAdminModel();
            if (admin.TenantId != tenantId) throw new ClientException("未配置租户", ClientLoggerSource.USER_ERROR);
            //# 生成token
            string token = JWTHelper.CreateToken(new JWTOptions(CoreSetting.Audience, CoreSetting.Issuer, CoreSetting.Expire),
                new[] {
                    new Claim("AdminId",admin.AdminId.ToString()),
                    new Claim("UserName",admin.UserName),
                    new Claim("IsDefault",admin.IsDefault.ToString()),
                    new Claim("TenantId",admin.TenantId.ToString()),
                    new Claim("RoleId",admin.RoleId.ToString()),
                     });
            //# 设置管理员token
            _adminUserCacheService.SetTenantToken(admin.AdminId, token);
            //# 读取配置
            string setting = _settingCacheService.GetSetting(SettingType.TenantDomain);
            Logger.Log($"登录租户“{tenantId}/{tenant.Name}”后台");
            return setting.Replace("{Domain}", tenant.Domain)
                          .Replace("{Token}", token);

        }
    }
}
